﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data;

namespace DarkCRM.Models
{
    [Serializable]
    public class Entity
    {
        private PropertyInfo[] mProperties;

        public virtual Entity Load(DataRow row)
        {
            if (mProperties == null)
            {
                mProperties = GetProperties();
            }

            foreach (PropertyInfo p in mProperties)
            {
                if (!p.IsSpecialName && p.CanRead && p.CanWrite)
                {
                    bool found = false;
                    foreach (DataColumn c in row.Table.Columns)
                    {
                        if (c.ColumnName.Equals(p.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found && !(row[p.Name] is DBNull))
                    {
                        p.SetValue(this, Convert.ChangeType(row[p.Name], p.PropertyType), null);
                    }
                }
            }

            return this;
        }

        public PropertyInfo[] GetProperties()
        {
            List<PropertyInfo> result = new List<PropertyInfo>();

            result.AddRange(this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy));

            //get property from interface
            Type[] interfaceTypes = this.GetType().GetInterfaces();
            foreach (Type type in interfaceTypes)
            {
                PropertyInfo[] interfaceProperties = type.GetProperties();
                foreach (PropertyInfo pi in interfaceProperties)
                {
                    var piCurrent = result.SingleOrDefault(i => i.Name.Equals(pi.Name, StringComparison.OrdinalIgnoreCase));
                    if (null == piCurrent)
                    {
                        result.Add(pi);
                    }
                }
            }

            return result.ToArray();
        }

    }
}